﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cannonball
{
    class GraphicsUtility
    {
        private static char DEFAULT_SYMBOL = '.';

        //Bresenham's line algorithm
        public static void DrawLine(int x0, int y0, int x1, int y1)
        {
            Console.ForegroundColor = ConsoleColor.DarkRed;
            int deltaX = Math.Abs(x1 - x0);
            int deltaY = Math.Abs(y1 - y0);
            int sx = x0 < x1 ? 1 : -1;
            int sy = y0 < y1 ? 1 : -1;
            int err = deltaX - deltaY;
            while (true)
            {
                DrawAtPosition(x0, y0);
                if (x0 == x1 && y0 == y1)
                {
                    break;
                }
                int err2 = 2 * err;
                if (err2 > -deltaY)
                {
                    err = err - deltaY;
                    x0 = x0 + sx;
                }
                if (x0 == x1 && y0 == y1)
                {
                    DrawAtPosition(x0, y0);
                    break;
                }
                if (err2 < deltaX)
                {
                    err = err + deltaX;
                    y0 = y0 + sy;
                }
            }
        }
        public static void DrawLine(int x0, int y0, int x1, int y1, char symb)
        {
            char temp = DEFAULT_SYMBOL;
            DEFAULT_SYMBOL = symb;
            DrawLine(x0, y0, x1, y1);
            DEFAULT_SYMBOL = temp;
        }
        private static void DrawAtPosition(int x, int y)
        {
            try
            {
                Console.SetCursorPosition(x, y);
                Console.Write(DEFAULT_SYMBOL);
            }
            catch (ArgumentOutOfRangeException e)
            {
                // Do nothing
            }
        }
    }
}
